package com.zyh.arrays;

public class MyArrays {
    /**
     * 冒泡排序
     * 选择排序
     * 二分查找
     */

    //冒泡排序
    public static int[] sort1(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }

    //    漂亮打印
    public static void toString(int[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                System.out.print(arr[i]);
            } else {
                System.out.print(arr[i] + ",");
            }
        }
        System.out.print("]");
    }

    //    二分查找
    public static int find(int[] arr, int key) {
//        数据校验
        if (arr == null || arr.length == 0) {
            System.out.println("数组有误！");
            return -1;
        }
        int min = 0, max = arr.length - 1, mid;
        while (min <= max) {
            mid = (max + min) / 2;
            if (key > arr[mid]) {//说明key在mid的右边
                min = mid + 1;
            } else if (key < arr[mid]) {//说明key在mid的左边
                max = mid - 1;
            } else {
                System.out.println(key + "在数组中的索引是：" + mid);
                return mid;
            }
        }
//        循环走完都没找到说明key不在数组中
        System.out.println(key + "不在数组中！");
        return -1;
    }

//    选择排序


    public static void main(String[] args) {
        int[] arr = {5, 3, 6, 1, 88, 9};
        int[] sort1 = sort1(arr);
//        toString(arr);
        int i = find(sort1, 2);
        if (i == -1) {
            return;
        }
    }
}
